using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web;

using Deepcode.Flux.Core.Services.FluxClient;
using Deepcode.Flux.Core.UI.Controls.Base;
using Deepcode.Flux.Core.Systems.CMS;

namespace Deepcode.Flux.Core.UI.Controls
{
	/// <summary>
	/// Content reference control
	/// </summary>
	[ValidationProperty("NodeID")]
	public class ContentLink : BaseControl, INamingContainer, IPostBackDataHandler
	{
		#region Properties
		/// <summary>
		/// Determines if the asset field can be empty or not. (note 
		/// this does not validate!) (default is true)
		/// </summary>
		public bool CanClear
		{
			get
			{
				object o = ViewState["CanClear"];
				if (o == null) return true;
				return (bool)o;
			}
			set
			{
				ViewState["CanClear"] = value;
			}
		}		/// <summary>
		/// Get/Set the ID of the selected node
		/// </summary>
		public int NodeID
		{
			get
			{
				object o = ViewState["NodeID"];
				if( o == null ) return -1;
				return (int) o;

			}
			set
			{
				ViewState["NodeID"] = value;
				if (this.SelectedText != null || this.SelectedID != null)
				{
					if (value == -1)
					{
						if (this.SelectedText != null) this.SelectedText.Text = "Nothing Selected";
						if (this.SelectedID != null) this.SelectedID.Value = "-1";
					}
					else
					{
						ContentManager cms = new ContentManager();
						ContentObject o = cms.AdxGetByID(value);
						if (o == null)
						{
							NodeID = -1;
						}
						else
						{
							if (this.SelectedText != null) this.SelectedText.Text = o.NodeTitle;
							if (this.SelectedID != null) this.SelectedID.Value = o.PK_ID.ToString();
						}
					}
				}
			}
		}
		#endregion
		#region Rendering override
		/// <summary>
		/// Render the control
		/// </summary>
		/// <param name="writer"></param>
		protected override void Render(HtmlTextWriter writer)
		{
			foreach( Control c in Controls )
				c.RenderControl( writer );
		}
		#endregion
		#region Initialisation
		/// <summary>
		/// Initialisation before rendering
		/// </summary>
		/// <param name="e"></param>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			
			Page.RegisterRequiresPostBack( this );
			
			// Register the script block
			this.LoadClientScript(
				"ContentLink/cl.js",
				"Deepcode.Flux.Core.UI.Controls.ContentLinkJS");

			// Load stylesheet
			this.LoadClientStyleSheet(
				"ContentLink/cl.css",
				"Deepcode.Flux.Core.UI.Controls.ContentLinkCSS");
		}
		#endregion
		#region Persistent Controls
		protected TextBox		SelectedText = null;
		protected HiddenField	SelectedID = null;
		#endregion
		#region Child control creation
		/// <summary>
		/// Creates the composite controls
		/// </summary>
		protected override void CreateChildControls()
		{
			// Load the Node ID
			string NodeText = "";
			ContentManager cms = new ContentManager( true );
			ContentObject o = cms.AdxGetByID( this.NodeID );
			if (o == null)
			{
				NodeID = -1;
				NodeText = "Nothing Selected";
			}
			else
			{
				NodeText = o.NodeTitle;
			}
			// Main div
			HtmlGenericControl HostDiv = new HtmlGenericControl("DIV");
			HostDiv.Attributes.Add( "id", this.ClientID );
			this.Controls.Add( HostDiv );

			// Selection items table and row
			HtmlTable SelectIconsTable = new HtmlTable();
			SelectIconsTable.CellSpacing = 0;
			SelectIconsTable.CellPadding = 2;
			SelectIconsTable.Border = 0;
			HostDiv.Controls.Add( SelectIconsTable );
			HtmlTableRow SelectIconsRow = new HtmlTableRow();
			SelectIconsTable.Controls.Add( SelectIconsRow );
			
			// Cell with textbox
			HtmlTableCell CellSelectedText = new HtmlTableCell();
			SelectIconsRow.Controls.Add( CellSelectedText );
			SelectedText = new TextBox();
			SelectedText.ID = "text";
			SelectedText.CssClass = "CL_Textbox";
			SelectedText.Text = NodeText;
			SelectedText.Enabled = false;
			if( this.Width != Unit.Empty ) SelectedText.Width = this.Width;
			else SelectedText.Width = new Unit("150px");
			CellSelectedText.Controls.Add( SelectedText );

			// Cell with select button
			HtmlTableCell CellSelectNew = new HtmlTableCell();
			SelectIconsRow.Controls.Add(CellSelectNew);
			ImageButton Button = new ImageButton();
			Button.ImageUrl = ClientHelper.GetFluxClientFile("ContentLink/img/select.gif");
			Button.OnClientClick = String.Format(
				"return CL_Select('{0}', '{1}');",
				this.ClientID,
				Page.ResolveUrl("~/"));
			CellSelectNew.Controls.Add(Button);

			// Cell with clear icon
			if (this.CanClear)
			{
				HtmlTableCell CellClear = new HtmlTableCell();
				SelectIconsRow.Controls.Add(CellClear);
				ImageButton Button2 = new ImageButton();
				Button2.ImageUrl = ClientHelper.GetFluxClientFile("ContentLink/img/remove.gif");
				Button2.OnClientClick = String.Format(
					"return CL_Clear('{0}');",
					this.ClientID);
				CellClear.Controls.Add(Button2);
			}

			// Register the hidden fields
			// Selected file 
			SelectedID = new HiddenField();
			SelectedID.ID = "value";
			SelectedID.Value = this.NodeID.ToString();
			HostDiv.Controls.Add( SelectedID );
		}
		#endregion
		#region IPostBackDataHandler Members
		/// <summary>
		/// Get the selected file if necessary and place it in
		/// the appropriate property.
		/// </summary>
		/// <param name="postDataKey"></param>
		/// <param name="postCollection"></param>
		/// <returns></returns>
		public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
		{
			// Process any value passed in on the value input first
			string s = postCollection[this.UniqueID + "$value"];
			int iValue = -1;
			try { iValue = Int32.Parse(s); } catch { iValue = -1; }
			
			// Check for differences
			if (this.NodeID != iValue )
				this.NodeID = iValue;

			return false;
		}
		/// <summary>
		/// Not used
		/// </summary>
		public void RaisePostDataChangedEvent()
		{
		}
		#endregion
	}
}
